/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
var buildTree = function (preorder, inorder) {
    let count = -1
    const iter = function (left, right) {
        count++
        if (left === right) {
            return new TreeNode(preorder[count])
        }
        let nodeIndex;
        let node = new TreeNode()
        for (let i = left; i <= right; i++) {
            if (inorder[i] == preorder[count]) {
                nodeIndex = i
                node.val = preorder[count]
                break
            }
        }
        if (left <= nodeIndex - 1)
            node.left = iter(left, nodeIndex - 1)
        if (nodeIndex + 1 <= right)
            node.right = iter(nodeIndex + 1, right)
        return node
    }
    return iter(0, inorder.length - 1)
};